import {
  ExecutionContext,
  SetMetadata,
  createParamDecorator,
} from '@nestjs/common';
import { Request } from 'express';
/**
 * 检查是否登录的装饰器
 * @returns
 */
export const RequireLogin = () => SetMetadata('require-login', true);
/**
 * 检查是否有该接口访问权限
 * @param permissions 权限
 * @returns
 */
export const RequirePermission = (...permissions: string[]) =>
  SetMetadata('require-permission', permissions);

/**
 * 获取用户信息
 * @param data 获取用户信息中的某个属性
 * @returns
 */
export const UserInfo = createParamDecorator(
  (data: string, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest<Request>();

    if (!request.user) {
      return null;
    }
    return data ? request.user[data] : request.user;
  },
);
